import { ref, computed } from 'vue';
import { UUID } from '@/util/rnd.js';
import { keydownCondPairs } from '../common.js';
import { picState } from './use-task.js';
import { selectLayer, setLayersVisible, useLayerCommon } from './use-layer-common.js';

export const labelSelectorProps = ref({ visible: false, style: {} });

export const lastSelectIndex = ref(0);
export const switchable = computed(() => ({
  prev: 0 < lastSelectIndex.value,
  next: lastSelectIndex.value + 1 < picState.value.layers.length,
}));

export function SwitchedLayer(sign) {
  return picState.value.layers[ lastSelectIndex.value + sign ];
};

export const autoAppendLayers = ref([]);

export function setAllAutoAppend() {
  autoAppendLayers.value = autoAppendLayers.value.length == picState.value.layers.length
  ? []
  : picState.value.layers;
}

export function setAutoAppend(layer) {
  if (autoAppendLayers.value.includes(layer)) {
    autoAppendLayers.value = autoAppendLayers.value.filter(item => item != layer);
    return;
  }

  autoAppendLayers.value.push( layer );
}

export function useLabelSelector(style) {
  labelSelectorProps.value.visible = true;
  labelSelectorProps.value.style = style;
}

/** @returns {import('../@types/index.js').Layer} */
export const Layer = (indexes, content) => ({
  id: UUID(),
  index: -1,
  label: void 0,
  start: Math.min(...indexes),
  end: Math.max(...indexes),
  content,
  color: 'transparent',
  memberOf: 'layers',
});

export const cloneLayer = layer => {
  const newLayer = R.clone(layer);
  newLayer.rectBoxProps.id = UUID();
  return newLayer;
};

export default function useLayer() {
  keydownCondPairs.push(
    [
      event => 'a' == event.key && event.ctrlKey,
      () => selectLayer('switch', 'all')
    ],
    [
      event => 'h' == event.key && event.ctrlKey,
      () => setLayersVisible('layers'),
    ],
  );

  useLayerCommon('layers');
}
